<template>
    <div class="common-layout">
        <el-container>
            <el-header class="header" style="color: black;height: 300px;">
                <el-card class="box-card " style="display:flex">
                    <el-avatar shape="square" :size="220" :fit="fit" :src="user.avatar" />
                </el-card>
                <el-card class="box-card">
                    <div class="common-layout">
                        <el-container>
                            <el-header class="header" style="height:20px">作者基本信息</el-header>
                            <el-main style="padding-bottom: 0;">
                                <el-descriptions :column="1" border>
                                    <div class="" descriptions-items>
                                        <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
                                        <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
                                        <el-descriptions-item label="余额">400</el-descriptions-item>
                                        <el-descriptions-item label="生日">{{ user.birthday }}</el-descriptions-item>
                                    </div>
                                </el-descriptions>
                            </el-main>
                            <el-footer
                                style="display: flex; justify-content: center; align-items: center; margin-top: 0;padding-top: 0;">
                                <el-button @click="goBack" type="primary">返回</el-button>
                            </el-footer>
                        </el-container>
                    </div>

                </el-card>
            </el-header>
            <el-main style="color: black;">
                <el-card style="width: 100%">
                    <div class="search-bar">
                        <el-input placeholder="搜索用户" v-model="searchQuery" clearable
                            style="width: 300px; margin-right: 10px">
                            <template #append>
                                <el-button icon="el-icon-search" @click="handleSearch">搜索</el-button>
                            </template>
                        </el-input>
                        <el-button type="primary" icon="el-icon-plus" @click="handleAddarticle">新增</el-button>
                    </div>
                    <el-table :data="current_articles" style="width: 100%; margin-top: 20px" border>
                        <el-table-column type="index" label="序号" width="200" :index="indexMethod"></el-table-column>
                        <el-table-column prop="title" label="文章标题" width="300"></el-table-column>
                        <el-table-column prop="content" label="文章内容" width="600"></el-table-column>
                        <el-table-column label="操作" width="300">
                            <template #default="scope">
                                <el-button size="mini" type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
                    </div>
                </el-card>
            </el-main>
        </el-container>
    </div>
    <!-- 新增，删除对话框 -->
    <el-dialog v-model="centerDialogVisible" :title="message" width="30%" align-center>
        <el-form>
            <el-form-item label="文章标题">
                <el-input v-model="input" placeholder="请输入" style="margin-bottom: 30px;" />
            </el-form-item>

            <el-form-item label="文本内容：">
                <el-input v-model="textarea" :rows="2" type="textarea" placeholder="请输入" />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="handleform">确认</el-button>
                <el-button @click="centerDialogVisible = false">
                    取消
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>


<script setup>

import { computed, ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';


const props = defineProps({
    username: String,  // 接收从父路由传递过来的用户名 prop
});

//响应式数据
const user = reactive({});
//列表要使用ref
const articles = ref([]);
const router = useRouter();
const total = ref(0);
const pageSize = ref(5);
const currentPage = ref(1);
const searchQuery = ref('');
const centerDialogVisible = ref(false);
const message = ref("编辑文章");
const input = ref("");
const textarea = ref("");
const isEdit = ref(true);
const Editform = ref({ id: "", username: "", title: "", content: "" })
const formToSubmit = ref({ id: "", username: "", title: "", content: "" })
const currentEditIndex = ref(0);
//异步，只进行一次，页面渲染时进行计算
onMounted(async () => {
    try {
        const response = await axios.get(`/api/users/getUserByUsername/${props.username}`);
        console.log('传给后端的 username 是：', props.username);
        const url = `/users/getUserByUsername/${props.username}`;
        console.log("请求的 URL: ", url); // 打印请求 URL，确保正确
        console.log(response);
        const data = response.data;
        Object.assign(user, data);
    }
    catch (error) {
        console.error("数据请求失败:", error)
    }

})

onMounted(async () => {
    try {
        const response = await axios.get(`/api/articles/author/${props.username}`);
        const data = response.data;
        articles.value = data;
        total.value = articles.value.length;
        console.log("数据的条数", total.value);
    }
    catch (error) {
        console.error("数据请求失败:", error);
    }
})
// 你可以在这里添加一些逻辑，用来获取特定作者的数据
//计算属性
//计算属性
const current_articles = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = currentPage.value * pageSize.value;
    return articles.value.slice(start, end)
});


const handleSizeChange = (val) => {
    pageSize.value = val;
}
const handleCurrentChange = (val) => {
    currentPage.value = val;
}
const goBack = () => {
    router.push('/homepage/manage-file');
}

const handleSearch = async () => {
    console.log('搜索内容:', searchQuery.value);
    //如果是空的话就是不执行的
    if (searchQuery.value == "") {
        return;
    }
    //假如不为空，我们就发到后端去更新数据
    else {
        try {
            const username = props.username;
            const name = searchQuery.value;
            const res = await axios.get('/api/articles/search', {
                params: { username, name },
            });
            const data = res.data;
            articles.value = data;
            console.log("data的值为", data);
            console.log("articles的值为", articles.value);

        } catch (err) {
            console.error('获取联系人失败:', err);
        }

    }
}

const indexMethod = (index) => {
    return index + 1
}

const handleAddarticle = () => {
    message.value = "新增文章"
    centerDialogVisible.value = true;
    isEdit.value = false;
    input.value = "";
    textarea.value = "";
}
// 用来编辑当行数据
const handleEdit = (index, row) => {
    message.value = "编辑文章"
    isEdit.value = true;
    centerDialogVisible.value = true;
    Editform.value = { ...row };

    console.log("666", Editform);
    input.value = Editform.value.title;
    textarea.value = Editform.value.content;
    currentEditIndex.value = index;
}
//用来处理表单
const handleform = async () => {

    if (isEdit.value) {
        // 更新本地数据
        articles.value[currentEditIndex.value].title = input.value;
        articles.value[currentEditIndex.value].content = textarea.value;
        // console.log("Editform before assign:", Editform.value);
        // // 准备提交的数据
        // Editform.value.title = input.value;
        // Editform.value.content = textarea.value;
        formToSubmit.value.id = articles.value[currentEditIndex.value].id;
        formToSubmit.value.username = articles.value[currentEditIndex.value].username;
        formToSubmit.value.title = articles.value[currentEditIndex.value].title;
        formToSubmit.value.content = articles.value[currentEditIndex.value].content;




        try {
            const response = await axios.post('/api/articles/update', formToSubmit.value);
            if (response.data === true) {
                console.log("编辑成功", response.data);
            } else {
                console.warn("后端返回失败", response.data);
            }
        } catch (err) {
            console.error("编辑失败", err.response || err);
        }
        centerDialogVisible.value = false;
    } else {
        // 这里你可以补上新增逻辑
        formToSubmit.value.username = props.username;
        formToSubmit.value.title = input.value;
        formToSubmit.value.content = textarea.value;
        const response = await axios.post("/api/articles/add", formToSubmit.value)
        if (response.data == true) {
            console.log("新增成功");
        }
        centerDialogVisible.value = false
        window.location.reload();

    }
};
const handleDelete = async (index, row) => {
    try {
        const response = await axios.delete(`/api/articles/${row.id}`);
        if (response.data === true) {
            console.log("删除成功");
            // 从前端数据中删除该项
            articles.value.splice(index, 1);


        } else {
            console.warn("删除失败", response.data);
        }
    } catch (error) {
        console.error("请求失败", error.response || error);
    }
    window.location.reload();
};

</script>

<style scoped>
/* 在这里添加作者主页的样式 */
.header {
    /* 设置成水平 */
    display: flex;
    /* 主轴元素分布，设置为中间平分 */
    justify-content: center;
}

.box-card {
    overflow: auto;
    /* 超出时显示滚动条 */
    margin: 20px;
    width: 40%;
    justify-content: center
}

.search-bar {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    height: 50px
}
</style>
